<template>
  <div class="allowance-container">
     <h2>员工月加班列表</h2>
    <!-- 顶部筛选栏 -->
    <div class="filter-bar">
      <div class="form-group inline">
        <label>选择月份:</label>
        <el-date-picker
          v-model="selectedMonth"
          type="month"
          format="YYYY-MM"
          value-format="YYYY-MM"
          placeholder="选择月份"
          @change="filterRecordsByMonth"
        />
      </div>
     
    </div>
     <button @click="showAddModal = true" class="add-button">添加津贴记录</button>

    <!-- 表格内容 -->
    <table class="allowance-table">
      <thead>
        <tr>
          <th>加班小时</th>
          <th>加班类型</th>
          <th>日期</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="record in paginatedList" :key="record.id">
          <td>{{ record.allowance_hour }}</td>
          <td>{{ record.allowance_type }}</td>
          <td>{{ formatDisplayDate(record.year_month) }}</td>
          <td>
            <button @click="editRecord(record)" class="edit-button">修改</button>
            <button @click="deleteRecord(record.id)" class="delete-button">删除</button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 空数据状态 -->
    <div v-if="filteredList.length === 0" class="empty-state">
      <i class="fa fa-inbox"></i>
      <p>暂无津贴记录</p>
    </div>

    <!-- 分页导航 -->
    <div class="pagination-container">
      <div class="total-count">
        共 {{ filteredList.length }} 条记录，分 {{ totalPages }} 页显示
      </div>

      <div class="pagination-numbers">
        <button @click="prevPage" :disabled="currentPage === 1" class="pagination-btn">
          <i class="fa fa-angle-left"></i> 上一页
        </button>

        <template v-if="totalPages > 1">
          <button 
            @click="currentPage = 1"
            class="pagination-number"
            :class="{ 'active': currentPage === 1 }"
          >
            1
          </button>
          
          <span v-if="currentPage > 4" class="pagination-ellipsis">...</span>
          
          <button
            v-for="page in getDisplayedPages"
            :key="page"
            @click="currentPage = page"
            class="pagination-number"
            :class="{ 'active': currentPage === page }"
          >
            {{ page }}
          </button>
          
          <span v-if="currentPage < totalPages - 3" class="pagination-ellipsis">...</span>
          
          <button 
            @click="currentPage = totalPages"
            class="pagination-number"
            :class="{ 'active': currentPage === totalPages }"
          >
            {{ totalPages }}
          </button>
        </template>

        <button @click="nextPage" :disabled="currentPage === totalPages" class="pagination-btn">
          下一页 <i class="fa fa-angle-right"></i>
        </button>
      </div>
    </div>

    <!-- 添加模态框 -->
    <div v-if="showAddModal" class="modal">
      <div class="modal-content">
        <h3>添加津贴记录</h3>
        <div class="form-group">
          <label>加班小时:</label>
          <input v-model.number="newRecord.allowance_hour" type="number" min="0" step="0.5" />
        </div>
        <div class="form-group">
          <label>加班类型:</label>
          <select v-model="newRecord.allowance_type" style="width: 100%;">
            <option value="普通加班">普通加班</option>
            <option value="节假日加班">节假日加班</option>
          </select>
        </div>
       
        <div class="form-group">
          <label>日期:</label>
          <el-date-picker
            v-model="newRecord.year_month"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
            @change="formatDate"
            style="width: 100%;"
          />
        </div>
        <div class="button-group">
          <button @click="addRecord" class="save-button">保存</button>
          <button @click="showAddModal = false" class="cancel-button">取消</button>
        </div>
      </div>
    </div>

    <!-- 编辑模态框 -->
    <div v-if="showEditModal" class="modal">
      <div class="modal-content">
        <h3>编辑津贴记录</h3>
        <div class="form-group">
          <label>加班小时:</label>
          <input v-model.number="editedRecord.allowance_hour" type="number" min="0" step="0.5" />
        </div>
        <div class="form-group">
          <label>加班类型:</label>
          <select v-model="editedRecord.allowance_type" style="width: 100%;">
            <option value="普通加班">普通加班</option>
            <option value="节假日加班">节假日加班</option>
          </select>
        </div>
        
        <div class="form-group">
          <label>日期:</label>
          <el-date-picker
            v-model="editedRecord.year_month"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
            @change="formatDate"
            style="width: 100%;"
          />
        </div>
        <div class="button-group">
          <button @click="updateRecord" class="save-button">保存</button>
          <button @click="showEditModal = false" class="cancel-button">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue';
import { ElDatePicker } from 'element-plus';
import 'element-plus/dist/index.css';
import axios from '../axios/index.js';

export default {
  name: 'AllowanceManager',
  components: {
    ElDatePicker
  },
  props: {
    userId: {
      type: [Number, String],
      required: true
    }
  },
  setup(props) {
    const userId = ref(props.userId);
    const allowanceList = ref([]);
    const showAddModal = ref(false);
    const showEditModal = ref(false);
    const selectedMonth = ref(new Date().toISOString().slice(0, 7));
    const newRecord = ref({ 
      allowance_hour: 0, 
      allowance_type: '普通加班', 
      year_month: '' 
    });
    
    const editedRecord = ref({ 
      id: null, 
      allowance_hour: 0, 
      allowance_type: '普通加班', 
      year_month: '' 
    });
    
    const currentPage = ref(1);
    const pageSize = ref(5);

    // 监听userId的变化
    watch(() => props.userId, (newVal) => {
      userId.value = newVal;
      fetchAllowanceRecords();
    });

    // 获取加班记录
    const fetchAllowanceRecords = async () => {
      if (!userId.value) {
        console.log('fetchAllowanceRecords: 用户ID为空，跳过获取');
        return;
      }
      try {
        console.log('fetchAllowanceRecords: 正在获取加班记录，用户ID:', userId.value);
        const response = await axios.get(`/allowance/${userId.value}`);
        console.log('fetchAllowanceRecords: API响应:', response);
        
        if (response.data && response.data.code === 200) {
          console.log('fetchAllowanceRecords: 获取到的加班记录:', response.data.data);
          allowanceList.value = response.data.data;
        } else {
          const errorMsg = response.data?.msg || '未知错误';
          console.error('fetchAllowanceRecords: 获取加班记录失败:', errorMsg);
          alert('获取加班记录失败：' + errorMsg);
        }
      } catch (error) {
        console.error('fetchAllowanceRecords: 获取加班记录失败:', error);
        if (error.response) {
          console.error('fetchAllowanceRecords: 错误响应:', error.response.data);
          alert('获取加班记录失败：' + (error.response.data?.msg || error.message));
        } else if (error.request) {
          console.error('fetchAllowanceRecords: 未收到响应:', error.request);
          alert('获取加班记录失败：服务器未响应');
        } else {
          console.error('fetchAllowanceRecords: 请求配置错误:', error.message);
          alert('获取加班记录失败：' + error.message);
        }
      }
    };

    // 生命周期钩子
    onMounted(async () => {
      if (userId.value) {
        await fetchAllowanceRecords();
      }
    });
    
    // 计算属性 - 根据月份筛选的记录
    const filteredList = computed(() => {
      if (!selectedMonth.value) return allowanceList.value;
      return allowanceList.value.filter(record => 
        record.year_month.startsWith(selectedMonth.value)
      );
    });
    
    // 计算属性 - 分页后的记录
    const paginatedList = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return filteredList.value.slice(start, end);
    });
    
    // 计算属性 - 总页数
    const totalPages = computed(() => {
      return Math.ceil(filteredList.value.length / pageSize.value);
    });
    
    // 计算属性 - 显示的页码范围
    const getDisplayedPages = computed(() => {
      let pages = [];
      if (totalPages.value <= 7) {
        pages = Array.from({ length: totalPages.value - 2 }, (_, i) => i + 2);
      } else if (currentPage.value <= 4) {
        pages = [2, 3, 4, 5, 6, 7];
      } else if (currentPage.value >= totalPages.value - 3) {
        pages = [
          totalPages.value - 6, 
          totalPages.value - 5, 
          totalPages.value - 4, 
          totalPages.value - 3, 
          totalPages.value - 2, 
          totalPages.value - 1
        ];
      } else {
        pages = [
          currentPage.value - 2, 
          currentPage.value - 1, 
          currentPage.value, 
          currentPage.value + 1, 
          currentPage.value + 2
        ];
      }
      return pages;
    });
    
    // 方法
    const formatDisplayDate = (dateStr) => {
      if (!dateStr) return '';
      const [year, month, day] = dateStr.split('-');
      const date = new Date(year, parseInt(month) - 1, parseInt(day));
      // 加一天
      date.setDate(date.getDate() + 1);
      return `${date.getFullYear()}年${String(date.getMonth() + 1).padStart(2, '0')}月${String(date.getDate()).padStart(2, '0')}日`;
    };
    
    const formatDate = () => {
      if (newRecord.value.year_month) {
        const date = new Date(newRecord.value.year_month);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        newRecord.value.year_month = `${year}-${month}-${day}`;
      }
      
      if (editedRecord.value.year_month) {
        const date = new Date(editedRecord.value.year_month);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        editedRecord.value.year_month = `${year}-${month}-${day}`;
      }
    };
    
    const filterRecordsByMonth = async () => {
      currentPage.value = 1; // 重置到第一页
      await fetchAllowanceRecords();
    };
    
    const addRecord = async () => {
      if (!userId.value) {
        alert('用户ID不能为空');
        return;
      }
      
      // 验证表单
      if (!newRecord.value.year_month) {
        alert('请选择日期');
        return;
      }
      
      if (newRecord.value.allowance_hour <= 0) {
        alert('加班小时数必须大于0');
        return;
      }
      
      try {
        const requestData = {
          user_id: userId.value,
          allowance_hour: newRecord.value.allowance_hour,
          allowance_type: newRecord.value.allowance_type,
          year_month: newRecord.value.year_month
        };
        
        console.log('发送添加请求:', requestData);
        const response = await axios.post('/allowance', requestData);
        console.log('添加响应:', response);
        
        if (response.data && response.data.code === 200) {
          await fetchAllowanceRecords();
          newRecord.value = { 
            allowance_hour: 0, 
            allowance_type: '普通加班', 
            year_month: '' 
          };
          showAddModal.value = false;
          alert('添加成功');
        } else {
          const errorMsg = response.data?.msg || '未知错误';
          console.error('添加加班记录失败:', errorMsg);
          alert('添加失败：' + errorMsg);
        }
      } catch (error) {
        console.error('添加加班记录失败:', error);
        if (error.response) {
          console.error('错误响应:', error.response.data);
          alert('添加失败：' + (error.response.data?.msg || error.message));
        } else if (error.request) {
          console.error('未收到响应:', error.request);
          alert('添加失败：服务器未响应');
        } else {
          console.error('请求配置错误:', error.message);
          alert('添加失败：' + error.message);
        }
      }
    };
    
    const editRecord = (record) => {
      editedRecord.value = { ...record };
      showEditModal.value = true;
    };
    
    const updateRecord = async () => {
      // 验证表单
      if (!editedRecord.value.year_month) {
        alert('请选择日期');
        return;
      }
      
      if (editedRecord.value.allowance_hour <= 0) {
        alert('加班小时数必须大于0');
        return;
      }
      
      try {
        const response = await axios.put(`/allowance/${editedRecord.value.id}`, {
          user_id: userId.value,
          allowance_hour: editedRecord.value.allowance_hour,
          allowance_type: editedRecord.value.allowance_type,
          year_month: editedRecord.value.year_month
        });
        
        if (response.data && response.data.code === 200) {
          await fetchAllowanceRecords();
          showEditModal.value = false;
          alert('更新成功');
        } else {
          const errorMsg = response.data?.msg || '未知错误';
          console.error('更新加班记录失败:', errorMsg);
          alert('更新失败：' + errorMsg);
        }
      } catch (error) {
        console.error('更新加班记录失败:', error);
        if (error.response) {
          console.error('错误响应:', error.response.data);
          alert('更新失败：' + (error.response.data?.msg || error.message));
        } else if (error.request) {
          console.error('未收到响应:', error.request);
          alert('更新失败：服务器未响应');
        } else {
          console.error('请求配置错误:', error.message);
          alert('更新失败：' + error.message);
        }
      }
    };
    
    const deleteRecord = async (id) => {
      if (confirm('确定要删除这条记录吗？')) {
        try {
          const response = await axios.delete(`/allowance/${id}`, {
            data: { user_id: userId.value }
          });
          if (response.data && response.data.code === 200) {
            await fetchAllowanceRecords();
            alert('删除成功');
          } else {
            const errorMsg = response.data?.msg || '未知错误';
            console.error('删除加班记录失败:', errorMsg);
            alert('删除失败：' + errorMsg);
          }
        } catch (error) {
          console.error('删除加班记录失败:', error);
          if (error.response) {
            console.error('错误响应:', error.response.data);
            alert('删除失败：' + (error.response.data?.msg || error.message));
          } else if (error.request) {
            console.error('未收到响应:', error.request);
            alert('删除失败：服务器未响应');
          } else {
            console.error('请求配置错误:', error.message);
            alert('删除失败：' + error.message);
          }
        }
      }
    };
    
    return {
      // 数据
      allowanceList,
      showAddModal,
      showEditModal,
      newRecord,
      editedRecord,
      currentPage,
      pageSize,
      selectedMonth,
      
      // 计算属性
      filteredList,
      paginatedList,
      totalPages,
      getDisplayedPages,
      
      // 方法
      formatDisplayDate,
      formatDate,
      filterRecordsByMonth,
      fetchAllowanceRecords,
      addRecord,
      editRecord,
      updateRecord,
      deleteRecord
    };
  }
};
</script>

<style scoped>
/* 样式保持不变 */
.allowance-container {
  padding: 20px;
  background-color: #ffffff; /* 设置背景色为白色 */
  color: #000000; /* 设置字体颜色为黑色 */
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.form-group.inline {
  display: flex;
  align-items: center;
  margin-right: 20px;
  width:100%;
}

.form-group.inline label {
  margin-right: 20px;
  margin-bottom: 0;
}

.add-button {
  background-color: #4CAF50;
    color: white;
    padding: 10px 15px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    margin-bottom: 15px;
}

.allowance-table {
  width: 100%;
  border-collapse: collapse;
}

.allowance-table th, .allowance-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.allowance-table th {
  background-color: #f2f2f2;
}

.edit-button, .delete-button {
  padding: 5px 10px;
  margin-right: 5px;
  cursor: pointer;
  border: none;
  border-radius: 3px;
}

.edit-button {
  background-color: #2196F3;
  color: white;
}

.delete-button {
  background-color: #f44336;
  color: white;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 400px;
  max-width: 90%;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
}

.form-group input, .form-group select {
  width: 95%;
  padding: 8px;
  border: 2px solid #ddd;
  border-radius: 4px;
}

.button-group {
  display: flex;
  justify-content: flex-end;
}

.save-button, .cancel-button {
  padding: 8px 15px;
  margin-left: 10px;
  cursor: pointer;
  border: none;
  border-radius: 4px;
}

.save-button {
  background-color: #4CAF50;
  color: white;
}

.cancel-button {
  background-color: #f44336;
  color: white;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.total-count {
  margin-top: auto;
  margin-bottom: auto;
}

.pagination-number {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  background-color: white;
  color: #333;
  transition: background-color 0.3s;
  margin: 0 2px;
}

.pagination-number.active {
  background-color: #2196F3;
  color: white;
  border-color: #2196F3;
  cursor: not-allowed;
}

.pagination-ellipsis {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #f8f9fa;
  color: #666;
  cursor: default;
  margin: 0 2px;
}

.pagination-btn {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  background-color: white;
  color: #333;
  transition: background-color 0.3s;
  margin: 0 2px;
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.empty-state {
  text-align: center;
  padding: 50px 0;
  color: #666;
}

.empty-state i {
  font-size: 40px;
  margin-bottom: 10px;
  color: #ccc;
}
h2 {
  color: #007bff;
  margin-bottom: 20px;
}
</style>